package com.example.mediaplayerdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

/**
 * @ClassName: MyImgView$
 * @Description: 图片手势
 * @Author: letquit
 * @CreateDate: 9/10/2021$
 * @Version: 1.0
 */
public class MyImgView extends AppCompatImageView implements View.OnTouchListener, ScaleGestureDetector.OnScaleGestureListener {

    boolean mBoo = true;
    Matrix matrix = new Matrix();
    ScaleGestureDetector scaleGestureDetector;

    public MyImgView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBoo) {
            matrix.postTranslate((getWidth() - getDrawable().getIntrinsicWidth()) / 2, (getHeight() - getDrawable().getIntrinsicHeight()) / 2);
            setImageMatrix(matrix);
            mBoo = false;
        }
    }

    public MyImgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOnTouchListener(this);
        scaleGestureDetector = new ScaleGestureDetector(context, this);
        setScaleType(ScaleType.MATRIX);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return scaleGestureDetector.onTouchEvent(motionEvent);
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
        float scaleFactor = scaleGestureDetector.getScaleFactor();
        matrix.postScale(scaleFactor, scaleFactor, getWidth() / 2, getHeight() / 2);
        Log.i("TAG", "Width：" + getWidth() + ", scaleFactor: " + scaleFactor);
        Log.i("TAG", "Height：" + getHeight() + ", scaleFactor: " + scaleFactor);
        setImageMatrix(matrix);
        return true;
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {

    }

}
